<?php
require_once getcwd() . '/service.impl/UserManager.php';
require_once getcwd() . '/models/User.php';
require_once getcwd() . '/library/Log.php';

	class AccountController extends MyController {
		
		private $manager;
		
		public function __construct(){
			$this->manager = new UserManager();
		}
		
		public function getAction($request){
			
		}
		
		public function postAction($request){
			Log::write("AccountController::post ");
			$dump = Log::var_dump($request);
			Log::write($dump);
			
			if(isset($request->url_elements[2]) and count($request->url_elements)==3 ){
				if(isset($_POST['deviceId']) and !empty($_POST['deviceId'])){
					$device_id  = $_POST['deviceId'];					
					$manager = $this->manager;
					$result = $manager->get($device_id);
					if($result->uid != null){
						$data['code']=200;
						$result->password="";						
						$data['account']=$result;
					}
					else {
						$data['code']= 500;
						$data['account']="No object";
					}
					
				}
			}
			else if($request->url_elements[2]=="update"){
				if(isset($_POST['deviceId']) and !empty($_POST['deviceId'])){
					$data = updateUser();
				}
				else{
					$data['account'] = '';
					$data['code'] = 400;
				}
			}
			else {
				$data['account'] = '';
				$data['code'] = 400;
			}
			return $data;
		}
		
		private function updateUser(){
			$id = $_POST['deviceId'];
			$login = $name = $password = $email = "";
			if(isset($_POST['name']))
				$name = $_POST['name'];
			if(isset($_POST['login']))
				$login= $_POST['login'];
			if(isset($_POST['pw']))
				$password= $_POST['pw'];
			if(isset($_POST['email']))
				$email= $_POST['email'];
			
			$user = new User($id);
			$user->name = $name;
			$user->login = $login;
			$user->access =$password;
			$user->email = $email;
			
			$mgr = $this->manager;
			$res = $mgr->update($user);
			
			if($res == 1 ){
				$data['code']=200;
				$data['message'] = "User informations updated";
				
			}
			else {
				$data['message']="internal error";
				$data['code']=500;
			}
			
			return $data;
		}	
		
	}





?>
